import Taro, { Component, Config } from '@tarojs/taro'
import { View, Image, Text } from '@tarojs/components'

import { AtButton }  from 'taro-ui'


import { IAddreddProps, IAddreddState } from './schemas'
import EditIcon from './edit.svg'
import './index.scss'
import { prefix } from '../../../utils'

export default class extends Component<IAddreddProps, IAddreddState> {
  config: Config = {
    navigationBarTitleText: '我的收货地址'
  }

  componentWillReceiveProps(nextProps) {
    console.log(this.props, nextProps)
  }

  componentWillUnmount() { }

  componentDidShow() { }

  componentDidHide() { }

  onGoPage = (id: number, e) => {
    e.stopPropagation()

    Taro.navigateTo({
      url: '/pages/my/address/Profile?id=' + id
    })
  }

  onNewAddress = e => {
    e.stopPropagation()

    // 提交收货地址
    Taro.chooseAddress()
    .then(data => {
      return Taro.request({
        method: 'POST',
        url: `${prefix}/api/v1/addresses`,
        data,
        header: {
        'content-type': 'application/json'
        }
      })
      .then(res => {
        console.log(res)
        Taro.showToast({ title: `地址保存成功`, icon: 'success', duration: 1000 })
      })
    })
    .catch(e => {
      console.log(e)
      Taro.showToast({ title: '操作失败', icon: 'loading', duration: 1000 })
    })
  }

  render() {
    return (
      <View className='address'>
        {
          Array.from(new Array(16)).map((i, k) =>
            (
              <View className='cell' key={i + k}>
                <View className='content'>
                  <View className='title'>
                    <Text className='text'>李泰爱 12345678910</Text>
                  </View>
                  <Text className='brief'>山西省 太原市 小店区 欢度鄂东大道</Text>
                </View>
                <View className='navigate'>
                  <Image src={EditIcon} className='icon' onClick={this.onGoPage.bind(this, k)} />
                </View>
              </View>
            )
          )
        }
        <View className='buttonFix'>
          <AtButton className='btn' type='primary' onClick={this.onNewAddress}>新增地址</AtButton>
        </View>
      </View>
    )
  }
}
